package com.shiro.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shiro.Result.BaseResult;
import com.shiro.Result.model.ResultModel;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: dengpeng
 * Date: 2018/6/29
 * Time: 17:40
 * Description: No Description
 */
public class JsonUtil {

    private static final Gson GSON = new Gson();

    /**
     * object转json
     *
     * @param o obj
     * @return String
     */
    public static String ObjectToJson(Object o) {

        return GSON.toJson(o);
    }

    /**
     * string 转json
     *
     * @param o   str
     * @param t   T.class
     * @param <T> t
     * @return T
     */
    public static <T> Object StringToObject(String o, T t) {

        return GSON.fromJson(o, (Type) t);
    }

    /**
     * string to List
     *
     * @param o   str
     * @param t   t
     * @param <T> T
     * @return obj
     */
    public static <T> Object stringToList(String o, T t) {

        return GSON.fromJson(o, new TypeToken<List<T>>() {
        }.getType());
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

        ResultModel resultModel = BaseResult.success();
        ResultModel resultModel1 = BaseResult.success();
        List<ResultModel> resultModels = Arrays.asList(resultModel, resultModel1);
        String s = JsonUtil.ObjectToJson(resultModels);
        System.out.println(s);

        //        resultModel = (ResultModel) JsonUtil.StringToObject(s, ResultModel.class);
        resultModels = (List<ResultModel>) JsonUtil.stringToList(s, ResultModel.class);
        System.out.println(resultModels);

    }
}
